package com.dotnet.modules.compact.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dotnet.common.utils.Constants;
import com.dotnet.common.utils.DateUtils;
import com.dotnet.common.web.BaseController;
import com.dotnet.modules.compact.entity.Compact;
import com.dotnet.modules.compact.entity.CompactPageVo;
import com.dotnet.modules.compact.entity.ContractType;
import com.dotnet.modules.compact.service.CompactService;
import com.dotnet.modules.compact.service.ContractTypeService;
import com.dotnet.modules.order.entity.Order;
import com.dotnet.modules.order.service.OrderService;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.page.Pagination;
import com.shishuo.cdn.entity.User;

/**
 * 
 * 描述：合同管理
 * 创建人： 高磊
 * 创建时间: 2016-7-4 上午8:50:15
 * @version
 */
@Controller
@RequestMapping("/compact")
public class CompactController extends BaseController {

	@Autowired
	private CompactService compactService;

	@Autowired
	private OrderService orderService;

	/**
	 * 
	 * 描述：合同管理   搜索  分页  
	 * 创建人： 高磊
	 * 创建时间: 2016-7-4 上午11:00:03
	 * @version
	 */
	@RequestMapping("/compactList")
	public String compactList(Integer pageNo,ModelMap model,HttpServletRequest request,Compact c,String startDate,String endDate) throws Exception {
		User user = getloginUser(request);
		StringBuilder params=new StringBuilder();
		CompactPageVo compact=new CompactPageVo();
		SimpleDateFormat sd=new SimpleDateFormat("MM/dd/yyyy");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		if(null!=startDate && StringUtils.isNotBlank(startDate) && null!=endDate && StringUtils.isNotBlank(endDate)){
			params.append("&startDate=").append(startDate).append("&endDate=").append(endDate);
			compact.setCreateTime(sdf.parse(sdf.format(sd.parse(startDate))));
			compact.setEndTime(sdf.parse(sdf.format(sd.parse(endDate))));
		}
		if(null!=c.getContractBianhao() && StringUtils.isNotBlank(c.getContractBianhao())){
			params.append("&c=").append(c.getContractBianhao());
			compact.setContractBianhao(c.getContractBianhao());
		}
		
		if(null!=user){
			compact.setUserId(user.getReg_tel());
		}
		compact.setPageNo(Pagination.cpn(pageNo));
		//可显示10行
		//compact.setPageSize(Constants.PAGE_SIZE);
		//显示2行
		compact.setPageSize(5);
		
		Pagination pagination=compactService.pagelist(compact);
		String url=request.getContextPath()+"/compact/compactList.do";
		pagination.pageView(url, params.toString());
		model.put("page", pagination);
		model.put("compact", c);
		model.put("startDate", startDate);
		model.put("endDate", endDate);
		return "/compact/compactlist";
	}

	/**
	 * 
	 * 描述：插入合同
	 * 创建人： 王小雷
	 * 创建时间: 2016-7-8 上午11:50:15
	 * @version
	 */
	@ResponseBody
	@RequestMapping("/insertContent")
	public Map<String, Object> insertContent(String orderNo, String orderId, String hetong, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Compact compact = new Compact();
		compact.setContractBianhao(orderNo);
		compact.setContractContent(hetong);
		compact.setCreateTime(DateUtils.getCurrentDate());
		compact.setStartTime(DateUtils.getCurrentDate());

		// session 取值
		User user = (User) request.getSession().getAttribute("user");
		String userid = user.getReg_tel().toString();
		compact.setUserId(userid);

		Compact c = new Compact();
		c.setContractBianhao(orderNo);
		Compact queryOne = compactService.queryOne(c);
		if (null == queryOne) {
			int i = compactService.add(compact);
			if (i > 0) {
				// 更改订单状态
				Order o = new Order();
				o.setId(Integer.valueOf(orderId));
				o.setOrderStatus(3);
				int x = orderService.updateByPrimaryKeySelective(o);
				if (x > 0) {
					map.put("status", true);
					map.put("msg", "签署成功，点击确定跳转至合同管理页面!");
				}
			} else {
				map.put("status", false);
				map.put("msg", "签署失败，请联系管理员!");
			}
		} else {
			// 更改订单状态
			Order o = new Order();
			o.setId(Integer.valueOf(orderId));
			o.setOrderStatus(3);
			orderService.updateByPrimaryKeySelective(o);
			map.put("status", false);
			map.put("msg", "已签署合同，请不要重复签署!");
		}
		return map;
	}

	/**
	 * 
	 * 描述：合同管理--查看合同    弹框
	 * 创建人： 高磊
	 * 创建时间: 2016-7-4 上午8:50:35
	 * @version
	 */
	@ResponseBody
	@RequestMapping("/compactdetail")
	public Map<String, Object> compactDetail(ModelMap model, String contractBianhao) {
		Map<String, Object> map = new HashMap<String, Object>();
		Compact compact = new Compact();
		compact.setContractBianhao(contractBianhao);
		Compact queryOne = compactService.queryOne(compact);
		if (null != queryOne) {
			map.put("status", true);
			map.put("info", queryOne.getContractContent());
		} else {
			map.put("status", false);
			map.put("info", "查看合同失败!");
		}
		return map;
	}

	@RequestMapping("/downloadCompact")
	public String downloadCompact(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Document document = new Document(PageSize.A4, 50, 50, 50, 50);
		User user = (User) request.getSession().getAttribute("user");
		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition", "attachment;filename=\"" + user.getReg_tel() + ".pdf\"");

		PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
		document.open();

		Compact compact = new Compact();
		compact.setId(Integer.valueOf(id));
		Compact queryOne = compactService.queryOne(compact);
		String classPath = request.getSession().getServletContext().getRealPath("/");
		setPdf(queryOne.getContractContent(), document, classPath, queryOne.getCreateTime());
		return null;
	}

	/**
	 * 
	 * 描述：设置pdf内容
	 * 创建人： 魏泽超
	 * 创建时间: 2016-3-31 下午5:10:22
	 * @version
	 * @throws ParseException 
	 */
	private void setPdf(String hetong, Document document, String classPath, Date time) throws DocumentException, IOException, ParseException {
		//SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		//Date old = sd.parse(time);
		//String startTime = sdf.format(time);
		String replaceStr = "";
		replaceStr = hetong.replace("<p>", "").replace("<center>", "").replace("<font size=\"+3\" color=\"red\">", "").replace("<font color=\"red\" size=\"+3\">", "").replace("</center>", "").replace("</font>", "</p>").replace("&nbsp;", "　");
		String[] str = replaceStr.split("</p>");
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
		Font titleFont = new Font(bfChinese, 20, Font.BOLD);
		Font fontChinese = new Font(bfChinese, 12, Font.BOLD);
		Chapter chapter1 = new Chapter(1);
		Paragraph pf = new Paragraph();
		for (int i = 0; i < str.length; i++) {
			if (1 == i) {
				pf = new Paragraph(str[i].replace(" ", ""), titleFont);
				pf.setAlignment(Element.ALIGN_CENTER);
				chapter1.add(pf);
				pf.setFirstLineIndent(25);
			} else {
				pf = new Paragraph("\n"+str[i], fontChinese);
				chapter1.add(pf);
				pf.setFirstLineIndent(25);
			}
		}
		Image image2 = Image.getInstance(classPath + "wsgz.gif");
		image2.scaleAbsolute(120f, 120f);
		image2.setAlignment(Element.ALIGN_LEFT);
		chapter1.add(image2);
		document.add(chapter1);
		document.close();
	}
}
